/*
	各种分类的subLevelbox集合.
	媒体分类. 视频分类.
 */
define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var util	= require('util');
	var SubLev	= require('@base/common/input').newSubLevelCheckbox;
	/*
		批量批入批出基础模块, 批出实际为内容复制而已.
	 */

	var BaseWithBatch = SubLev.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				'urlIds': 'category/listByIds'
				,'exportUri': 'modules/port.export'
				,'importUri': 'modules/port.import'
				// 是否带操作
				,'hasOperate': false
				// 是否带导入导出
				,'hasImExport': false
				,'imExportTitle': '分类数据'
				,'imExportParam': {}
				,'hideZoneHead': true
				,'view_model': {
					'operator': [
						//{'name': LANG('反选'), 'id': 'reverse'},
						{'name': LANG('清空'), 'id': 'clear'}
					],
					'imExport': [
						{'name': LANG('批量导出'), 'id': 'export'},
						{'name': LANG('批量导入'), 'id': 'import'}
					],
					value: [],
					selectItemLength: 0,
					operateEvent: this.vmOperateEvent.bind(this)
				}
			});

			this.Super('init', arguments);
		}
		,afterBuild: function()
		{
			this.Super('afterBuild', arguments);
			var el = this.getDOM();
			var c = this.getConfig();
			if(c.hasOperate || c.hasImExport)
			{
				var doms = this.doms || {};
				doms.buttom = $('<div class="M-commonSLCButtom" />').appendTo(el);
				if(c.hasOperate)
				{
					doms.buttom.append([
						'<button class="btn btn-default mr5 mt10 fr" ms-repeat-op="operator" ms-click="operateEvent(op.id)">{{op.name}}</button>'
					].join(''));
				}
				if(c.hasImExport)
				{
					doms.buttom.append([
						'<button class="btn btn-default mr5 mt10 fr" ms-repeat-op="imExport" ms-click="operateEvent(op.id)">{{op.name}}</button>'
					].join(''));
				}

				this.buildFromTemplate();
			}

			if(c.auto_load)
			{
				this.load();
			}
		}
		,vmOperateEvent: function(type) {
			switch (type) {
				case 'export':
					if(!this.$selected) {
						pubjs.alert(LANG('请先选择相应的分类才可以导出'));
					}
					else {
						this.batchPop(type);
					}
					break;
				case 'import':
					this.batchPop(type);
					break;
				case 'clear':
					this.setData([]);
					break;
				case 'reverse':
					this.reverse();
					break;
			}
		}
		/*
		 批量导入导出方法
		 */
		,batchPop: function(type) {
			var self = this;
			var c = self.getConfig();
			if(!c.importUri)
			{
				return pubjs.alert('请指定导入导出模块路径');
			}

			if(type == 'export') {
				pubjs.loading.show();
				pubjs.mc.send(
					c['urlIds']
					,$.extend({ids: self.$selected, mongoField: ['BdxId', 'Name']},c.param, c.imExportParam)
					,self.afterExport.bind(self)
				);
			}
			else {
				var mod = this.$ && this.$.imPop;
				if(!mod) {
					this.createAsync('imPop',c.importUri, function(mod) {
						mod.setTitle(c.imExportTitle  + LANG('导入')).show();
					})
				}
				else {
					mod.show();
				}
			}
		}
		,afterExport: function(err, data) {
			pubjs.loading.hide();
			if(err) {
				pubjs.error(err);
				return false;
			}

			var c = this.getConfig();
			if(!c.exportUri)
			{
				return pubjs.alert('请指定导入导出模块路径');
			}

			var code = '';
			util.each(data, function(item){
				code += [item[c.valueKey], item[c.nameKey]].join('\t\t') + '\n';
			});

			var mod = this.$ && this.$.exPop;
			if(!mod) {
				this.createAsync('exPop', c.exportUri, function(mod) {
					mod.setTitle(c.imExportTitle  + LANG('导出')).setData(code).show();
				})
			}
			else {
				mod.setData(code).show();
			}
		}
		,onImportList: function(ev){
			var importIds = ev.param.list.join();
			if(importIds)
			{
				this.setData((this.$selected || []).concat(importIds.split(',')));
			}
		}
	});


	var Base = BaseWithBatch.extend({
		init:function(config){
			config = pubjs.conf(config, {
				"key":"children"
				,"valueKey":"BdxId"
				,"nameKey":"Name"
				,"silence":false
				,'auto_load': true
				,'getSubs': true
				,'reqType': 'websocket'	//ajax
				,'url': 'category/media'
				,'param': {
					'Layer': 2,
					'ChannelId': 0
				}
			});

			this.Super('init', arguments);
		}
		,setParam: function(param){
			var c = this.getConfig();
			c.param = $.extend(c.param, param);
			return this;
		}
		,load: function(cb){
			if(!this.$checkDOM){
				this.$checkDOM = this.getDOM();
			}
			if (!util.checkUI(this.$checkDOM, 'load', this, cb)){
				return this;
			}
			var c = this.getConfig();
			if(c.reqType == 'websocket') {
				pubjs.mc.send(c.url , c.param, this.onData.bind(this), cb);
			}
			else {
				pubjs.data.get(c.url, c.param, this, 'onData', cb);
			}
			return this;
		}
		,onData: function(err, data, cb){
			if (err){
				pubjs.error(err);
			}else {
				var c = this.getConfig();
				if(pubjs.config('exchange_group/youku').indexOf(c.param.ChannelId) > -1 && c.url.indexOf('channel') > -1) {
					this.setList(data);
				}
				else {
					this.setList([{Name:LANG('全部'), _id:0, children:data}]);
					//this.setList(data);
				}
			}
			if (cb){
				cb();
			}
		}
		,getData: function(detail){
			var list = this.Super("getData");
			if(detail){
				return {'list': list};
			}else {
				return list;
			}
		}
		,reset: function() {
			this.Super('reset', arguments);
			return this;
		}
	});

	exports.media = Base;
	exports.base = SubLev;

	var Media = Base;
	// 视频分类
	var Video = Media.extend({
			init:function(config){
				config = pubjs.conf(config, {
					"key":"children"
					,"valueKey":"BdxId"
					,"nameKey":"Name"
					,"silence":false
					,'auto_load': false
					,'getSubs': true
					,'url': ''
					,'reqType': 'websocket'	//todo 当各种分类导入数据库后,这里要求是websocket,现在只是为了测试界面.
					,'param': null
				});

				this.Super('init', arguments);
			}
			,setParam: function(param){
				var self = this;
				var c = self.getConfig();
				c.param = $.extend(c.param, param);
				c.url = 'category/video';//self.$url_map[param.ChannelId];
				return self;
			}
		}
	);

	exports.video = Video;
	var MobileApp = Video.extend({
			init: function(config){
				config = pubjs.conf(config, {
					"key":"children"
					,"valueKey":"BdxId"
					,"nameKey":"Name"
					,"silence":false
					,'auto_load': false
					,'getSubs': true
					,'param': null
					,'hideZoneHead': false
					,'url': 'category/app'
				});

				this.Super('init', arguments);
			}
			,setParam: function(param){
				var self = this;
				// 是不是聚效移动
				var isJuxiaoMobiel = param.ChannelId === 10033;
				var layerParam = isJuxiaoMobiel ? {'Layer': 3} : {};

				var c = self.getConfig();
				c.param = $.extend(c.param, param, layerParam);

				// 如果是聚效移动的时候，现实三级
				var con = this.getDOM().parent();
				if (con && con.toggleClass)
				{
					con.toggleClass('P-adsGroupEditMedia', !isJuxiaoMobiel);
				}

				return self;
			}
		}
	);
	exports.mobileApp = MobileApp;

	var SohuVideo = Video.extend({
			init:function(config){
				config = pubjs.conf(config, {
					"key":"children"
					,"valueKey":"BdxId"
					,"nameKey":"Name"
					,"silence":false
					,'auto_load': false
					,'getSubs': true
					,'url': ''
					,'param': null
				});

				this.Super('init', arguments);
			}
		}
	);
	exports.sohuVideo = SohuVideo;

	var SohuChannel = BaseWithBatch.extend({
			init: function(config){
				config = pubjs.conf(config, {
					"key":"children"
					,"valueKey":"BdxId"
					,"nameKey":"Name"
					,'silence':false
					,'auto_load': false
					,'reqType': 'websocket'
					,'url': 'category/channel'
					,'hideZoneHead': false
					,'param': {
						Layer: 3
					}
					,'class': 'M-commonSLC M-commonSLCChannelClass'
				});

				this.Super('init', arguments);
			}
			,afterBuild: function()
			{
				this.Super('afterBuild', arguments);
				var c = this.getConfig();
				this.$item = $('<div class="M-formItem">').appendTo(c.target);
				$('<label class="M-formItemLabel"/>').text(c.label).appendTo(this.$item);
				this.$el.appendTo(this.$item);
			}
			,setParam: function(param){
				var c = this.getConfig();
				c.param = $.extend(c.param, param);
				return this;
			}
			,load: function(cb){
				var c = this.getConfig();
				if(c.reqType == 'websocket') {
					pubjs.mc.send(c.url , c.param, this.onData.bind(this), cb);
				}
				else {
					pubjs.data.get(c.url, c.param, this, 'onData', cb);
				}
				return this;
			}
			,onData: function(err, data, cb){
				if (err){
					pubjs.error(err);
				}else {
					this.setList(data && data.items || []);
				}
				if (cb){
					cb();
				}
			}
			,getData: function(){
				return this.Super("getData",arguments);
/*				var c = this.getConfig();
				var merge = !c.getSubs;
				var ret = [];
				// 获取项目数据
				var dom, input, total, check, i, body = this.doms.body;
				var doms = body.find('.M-commonSLCItem');
				for (i=0; i<doms.length; i++){
					dom = doms.eq(i);
					input = dom.children('input');
					if (input.length){
						if (input.prop('checked') && input.val() !== ''){
							ret.push(input.val());
						}
					}else {
						total = dom.find('.M-commonSLCSub input');
						check = total.filter(':checked');
						input = dom.find('.M-commonSLCItemHead > input');
						if (total.length > 0 && check.length && input.val() !== ''){
							ret.push(input.val());
							if (merge){ check = false; }
						}
						if (check){
							for (var j=0; j<check.length; j++){
								input = check.eq(j);
								if (input.val() !== ''){
									ret.push(input.val());
								}
							}
						}
					}
				}
				// 获取分区数据
				doms = body.find('.M-commonSLCZoneHead > input[value!=""]');
				for (i=0; i<doms.length; i++){
					input = doms.eq(i);
					if (input.prop('checked')){
						ret.push(input.val());
					}
				}

				this.$selected = ret;
				return ret;*/
			}
			,setData: function(sels){
				this.Super("setData",arguments);
				return this;
/*				this.reset();
				if (!sels || !sels.length){
					return;
				}
				this.$selected = sels;

				var i,map = {};
				for (i=sels.length-1; i>=0; i--){
					map[sels[i]] = 1;
				}

				var dom, body = this.doms.body;
				var doms = body.find('input[value!=""]');
				for (i=doms.length-1; i>=0; i--){
					dom = doms.eq(i);
					if (map[dom.val()]){
						dom.prop('checked', true);
					}
				}

				// 更新项目状态
				var total, check, input;
				doms = body.find('.M-commonSLCSub');
				for (i=0; i<doms.length; i++){
					dom = doms.eq(i);
					input = dom.prev().children('input');
					total = dom.find('input');
					check = total.filter(':checked');

					if (check.length > 0 && check.length < total.length){
						dom.next().css('display', 'block').text(check.length + '/' + total.length);
					}

				}*/
			}
			,hide: function(){
				this.Super('hide', arguments);
				this.$item.hide();
			}
			,show: function(){
				this.Super('show', arguments);
				this.$item.show();
			}
		}
	);
	exports.sohuChannel = SohuChannel;

	var MogoApp = SohuChannel.extend({
		init: function(config){
			config = pubjs.conf(config, {
				"key":"children"
				,"valueKey":"BdxId"
				,"nameKey":"Name"
				,'silence':false
				,'auto_load': false
				,'url': 'category/app'
				,'param': {
					Layer: 3
				}
				,'class': 'M-commonSLC M-commonSLCMongoAppClass'
			});

			this.Super('init', arguments);
		}
	});

	exports.mogoApp = MogoApp;
});